/*
 * 显示目录下面文件
 * @author li.xiaoxi
 * @date: 2016-12-15
 */
var fs = require('fs');

function fileNamesFn(directory){
  var oriPath = directory||'';
  directory = (directory && (process.cwd()+directory))||process.cwd();
  var nameRes = [],
      dirRes = [],
      files;

  //容错处理
  try {
    files = fs.readdirSync(directory)||[]
    files.forEach(function(file){
      var stat = fs.lstatSync(directory+'/'+file),
          ori = file;
      if(oriPath) {
        ori = oriPath+'/'+file;
      }

      if(!stat.isDirectory()) {
        nameRes.push(ori);
      }else {
        dirRes.push(ori);
      }
    });

    return {
      nameRes: nameRes,
      dirRes: dirRes
    };

  }catch(err){
    //console.log('================hello==========')
  }

}

function showFn(dir){
  var filenames = fileNamesFn(dir);
  var h1_file = '<h2>文件列表</h2>',
      h1_dir = '<h2>目录列表</h2>',
      file_arr = [],
      dir_arr = [];

  if(filenames && filenames.nameRes.length) {
    file_arr.push(h1_file);
    filenames.nameRes.forEach(function(item){
      file_arr.push('<p><a href="'+item+'" >'+ item+'</a></p>');
    });
  }

  if(filenames && filenames.dirRes.length) {
    dir_arr.push(h1_dir);
    filenames.dirRes.forEach(function(item){
      dir_arr.push('<p><a href="'+item+'" >'+ item+'</a></p>');
    });
  }

  return file_arr.join('')+dir_arr.join('');
}

exports.showFileNames = showFn;
